//
//  LVBaseCollectionViewVC.m
//  ListViewModel
//
//  Created by 曹连华 on 2022/7/14.
//

#import "LVBaseCollectionViewVC.h"
#import "LVBaseSectionHeaderFooterReusableView.h"

#define WEAK_SELF __weak typeof(self)weakSelf = self;
#define STRONG_SELF __strong typeof(weakSelf)self = weakSelf;

@interface LVBaseCollectionViewVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> {
    NSIndexPath *beganIndexPath;
}

@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation LVBaseCollectionViewVC

- (LVBaseCollectionViewModel *)viewModel {
    if(!_viewModel) {
        _viewModel = [[LVBaseCollectionViewModel alloc]init];
    }
    return _viewModel;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc]initWithFrame:UIScreen.mainScreen.bounds collectionViewLayout:[self collectionViewFlowLayout]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self.viewModel.dataSource;
        _collectionView.backgroundColor = UIColor.whiteColor;
        UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
        [_collectionView registerClass:LVBaseSectionHeaderFooterReusableView.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:LVBaseSectionHeaderFooterReusableView.reuseIdentifier];
        [_collectionView registerClass:LVBaseSectionHeaderFooterReusableView.class forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:LVBaseSectionHeaderFooterReusableView.reuseIdentifier];
        [_collectionView addGestureRecognizer:tap];

    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.viewModel.dataSource resetDataSource:self];
    
    [self addCollectionView];
    
    [self reloadCollectionBlock];
    
}

- (void)addCollectionView {
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.collectionView];
}

- (void)reloadCollectionBlock {
    WEAK_SELF
    self.viewModel.reloadCollectionBlock = ^(NSIndexSet * _Nullable sections, NSArray<NSIndexPath *> * _Nullable indexPaths) {
        STRONG_SELF
        if(sections) {
            [self.collectionView reloadSections:sections];
        } else if (indexPaths) {
            [self.collectionView reloadItemsAtIndexPaths:indexPaths];
        } else {
            [self.collectionView reloadData];
        }
    };
}

- (void)actionsBlock {
    WEAK_SELF
    self.viewModel.dataSource.moveRowModelBlock = ^(RowModelEditOperateResultBlock  _Nullable operateResultBlock, NSIndexPath * _Nullable sourceIndexPath, NSIndexPath * _Nullable destinationIndexPath) {
        operateResultBlock(YES);
        STRONG_SELF
        [self.collectionView reloadData];
    };
    
    self.viewModel.showLoadingBlock = ^(NSString *message) {};
    self.viewModel.hideLoadingBlock = ^(NSString *message) {};
    self.viewModel.makeToastBlock = ^(NSString *message) {};
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.viewModel didSelectedRowModelWithIndexPath:indexPath];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    LVBaseCellRowModel *rowModel = [self.viewModel.dataSource rowModelAtIndex:indexPath];
    return rowModel.rowSize;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    LVBaseCellSectionModel *sectiobModel = [self.viewModel.dataSource sectionModelAtIndex:section];
    return sectiobModel.sectionInset;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    LVBaseCellSectionModel *sectiobModel = [self.viewModel.dataSource sectionModelAtIndex:section];
    return sectiobModel.minimumLineSpacing;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    LVBaseCellSectionModel *sectiobModel = [self.viewModel.dataSource sectionModelAtIndex:section];
    return sectiobModel.minimumInteritemSpacing;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    LVBaseCellSectionModel *sectiobModel = [self.viewModel.dataSource sectionModelAtIndex:section];
    return sectiobModel.sectionHeader.size;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    LVBaseCellSectionModel *sectiobModel = [self.viewModel.dataSource sectionModelAtIndex:section];
    return sectiobModel.sectionFooter.size;
}

#pragma mark - UICollectionViewDataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    LVBaseCellSectionModel *sectionModel = [self.viewModel.dataSource sectionModelAtIndex:indexPath.section];
    LVBaseSectionHeaderFooterModel *headerModel = sectionModel.sectionHeader;
    LVBaseSectionHeaderFooterModel *footerModel = sectionModel.sectionFooter;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        LVBaseSectionHeaderFooterReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:LVBaseSectionHeaderFooterReusableView.reuseIdentifier forIndexPath:indexPath];
        [header updateWithHeaderFooterModel:headerModel atIndexPath:indexPath];
        return header;

    } else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        LVBaseSectionHeaderFooterReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:LVBaseSectionHeaderFooterReusableView.reuseIdentifier forIndexPath:indexPath];
        [footer updateWithHeaderFooterModel:footerModel atIndexPath:indexPath];
        return footer;

    }
    return nil;
}
- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    //获取此次点击的坐标，根据坐标获取cell对应的indexPath
    CGPoint point = [longPress locationInView:self.collectionView];
    NSIndexPath *sourceIndexPath = [self.collectionView indexPathForItemAtPoint:point];
    //根据长按手势的状态进行处理。
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            //当没有点击到cell的时候不进行处理
            if (!sourceIndexPath) {
                break;
            }
            //开始移动
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:sourceIndexPath];
            beganIndexPath = [NSIndexPath indexPathForRow:sourceIndexPath.row inSection:sourceIndexPath.section];
            break;
        case UIGestureRecognizerStateChanged:{
            NSIndexPath *destinationIndexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (destinationIndexPath) {
                LVBaseCellRowModel *beganRowModel = [self.viewModel.dataSource rowModelAtIndex:beganIndexPath];
                if (beganRowModel.canMove == NO ||destinationIndexPath.section != beganIndexPath.section) {
                    [self.collectionView cancelInteractiveMovement];
                } else {
                    [self.collectionView updateInteractiveMovementTargetPosition:point];
                }
            }
        }
            break;
        case UIGestureRecognizerStateEnded:{
            NSIndexPath *destinationIndexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (destinationIndexPath) {
                LVBaseCellRowModel *row = [self.viewModel.dataSource rowModelAtIndex:destinationIndexPath];
                if (row.canMove == NO) {
                    [self.collectionView cancelInteractiveMovement];
                }
            }
            //停止移动调用此方法
            [self.collectionView endInteractiveMovement];
            
        }
            break;
        default:
            //取消移动
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

- (UICollectionViewFlowLayout *)collectionViewFlowLayout {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumLineSpacing = 5;
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.headerReferenceSize = CGSizeMake(50, 50);
    flowLayout.footerReferenceSize = CGSizeMake(50, 50);
    flowLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width-20)/3, 100);
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    return flowLayout;
}
@end
